package com.ragdollcat.thirdaicodegenerate.controller;

import cn.hutool.core.util.ObjUtil;
import com.mybatisflex.core.paginate.Page;
import com.ragdollcat.thirdaicodegenerate.annotation.AuthCheck;
import com.ragdollcat.thirdaicodegenerate.common.BaseResponse;
import com.ragdollcat.thirdaicodegenerate.common.ResultUtils;
import com.ragdollcat.thirdaicodegenerate.constants.UserConstant;
import com.ragdollcat.thirdaicodegenerate.exception.ErrorCode;
import com.ragdollcat.thirdaicodegenerate.exception.ThrowUtils;
import com.ragdollcat.thirdaicodegenerate.model.dto.chathistory.ChatHistoryQueryRequest;
import com.ragdollcat.thirdaicodegenerate.model.entity.ChatHistory;
import com.ragdollcat.thirdaicodegenerate.model.entity.User;
import com.ragdollcat.thirdaicodegenerate.service.ChatHistoryService;
import com.ragdollcat.thirdaicodegenerate.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 对话历史 控制层。
 *
 * @author Administrator
 */
@RestController
@RequestMapping("/chatHistory")
public class ChatHistoryController {

    @Resource
    private ChatHistoryService chatHistoryService;

    @Resource
    private UserService userService;

    /**
     * 分页查询对话历史（使用游标）
     * 普通用户查询
     */
    @GetMapping("/queryByPage/{appId}")
    public BaseResponse<Page<ChatHistory>> getChatHistoryByPage(@PathVariable("appId") Long appId,
                                                               @RequestParam(defaultValue = "10") int pageSize,
                                                               @RequestParam(required = false) LocalDateTime localDateTime,
                                                               HttpServletRequest request) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(appId) || appId < 0L, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(pageSize > 50,ErrorCode.PARAMS_ERROR);
        User user = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjUtil.isEmpty(user), ErrorCode.NOT_LOGIN_ERROR);
        return ResultUtils.success(chatHistoryService.getChatHistoryByPage(appId,pageSize,localDateTime,user));
    }


    /**
     * 分页查询对话历史（使用游标）
     * 管理员查询
     */
    @PostMapping("/admin/queryByPage")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ChatHistory>> getChatHistoryByPage4Admin(@RequestBody ChatHistoryQueryRequest chatHistoryQueryRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(chatHistoryQueryRequest), ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(chatHistoryService.getChatHistoryByPage4Admin(chatHistoryQueryRequest));
    }
}
